package com.jianshuge.app.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import com.jianshuge.app.AppContext;
import com.jianshuge.app.AppException;
import com.jianshuge.app.R;

import com.jianshuge.app.adapter.ListViewBookshelfAdapter;
import com.jianshuge.app.adapter.ListViewRecentTrendsAdapter;
import com.jianshuge.app.bean.Bookshelf;
import com.jianshuge.app.bean.BookshelfList;
import com.jianshuge.app.bean.FriendList;
import com.jianshuge.app.bean.Notice;
import com.jianshuge.app.bean.MyResult;
import com.jianshuge.app.bean.User;


import com.jianshuge.app.bean.Behavior;
import com.jianshuge.app.bean.BehaviorList;


import com.jianshuge.app.common.StringUtils;
import com.jianshuge.app.common.UIHelper;
import com.jianshuge.app.widget.PullToRefreshListView;
import com.jianshuge.app.widget.UserInfoDialog;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;

/**
 * 用户专页
 */
public class UserCenter extends BaseActivity{
	
	private ImageView mBack;
	private ImageView mRefresh;
	private TextView mHeadTitle;
	private ProgressBar mProgressbar;
	private RadioButton mRelation;
	private RadioButton mMessage;
	private RadioButton mAtme;
	private UserInfoDialog mUserinfoDialog;
	private Button mTabActive;
	private Button mTabFavorite;
	
	private ImageView mUserface;
	private TextView mUsername;
	private TextView mFrom;
	private TextView mSignature;
	private TextView mJointime;
	
	private TextView mUBL;
	private TextView mFBL;
	private TextView mCBL;
	private TextView mPBL;

	private TextView mFavorites;
	private TextView mFriends;
	private TextView mFollowers;
	
	private TextView mVoteCnt;
	private TextView mBeVotedCnt;
	private TextView mLatestonline;
	
	private PullToRefreshListView lvActive;
	private ListViewRecentTrendsAdapter lvActiveAdapter;
	private List<Behavior> lvActiveData = new ArrayList<Behavior>();
	private View lvActive_footer;
	private TextView lvActive_foot_more;
	private ProgressBar lvActive_foot_progress;
    private Handler mActiveHandler;
	private int lvActiveSumData;
	
	private PullToRefreshListView 		lvBookshelf;
	private ListViewBookshelfAdapter 	lvBookshelfAdapter;
	private List<Bookshelf> lvBookshelfData = new ArrayList<Bookshelf>();
	private View lvBookshelf_footer;
	private TextView lvBookshelf_foot_more;
	private ProgressBar lvBookshelf_foot_progress;
    private Handler lvBookshelfHandler;
	private int lvBookshelfSumData;
    
    private User mUser;
    private Handler mUserHandler;
	private int relationAction;	
	private int curLvActiveDataState;
	private int curLvBookshelfDataState;	
	
	private AppContext appContext;// 全局Context
	
	private ProgressDialog mMyProgress;
	
	private int _uid;
	private int _hisuid;
	private String _hisname;
	private String _username;
	private int _pageSize = 10;
	
	private final static int DATA_LOAD_ING = 0x001;
	private final static int DATA_LOAD_COMPLETE = 0x002;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_center);
		
		appContext = (AppContext) getApplication();
		
		this.initView();
		
		this.initData();
	}
	
    //初始化视图控件
    private void initView()
    {
    	_hisuid = getIntent().getIntExtra("his_id", 0);
    	_hisname = getIntent().getStringExtra("his_name");
    	_username = getIntent().getStringExtra("his_name");
    	_uid = appContext.getLoginUid();
    	
    	mBack = (ImageView)findViewById(R.id.user_center_back);
    	mRefresh = (ImageView)findViewById(R.id.user_center_refresh);
    	
    	mHeadTitle = (TextView)findViewById(R.id.user_center_head_title);
    	mProgressbar = (ProgressBar)findViewById(R.id.user_center_head_progress);
    	
    	//////////////////////////////////////////////////////////////////////////
    	mRelation = (RadioButton)findViewById(R.id.user_center_footbar_relation);

    	//////////////////////////////////////////////////////////////////////////
    	
    	mMessage = (RadioButton)findViewById(R.id.user_center_footbar_message);
    	mAtme = (RadioButton)findViewById(R.id.user_center_footbar_atme);
    	
    	if( _uid == _hisuid ) {
    		mRelation.setVisibility(View.GONE);
    		mMessage.setText("我的好友");
    		mAtme.setText("我的书单");
    	}
    	
    	mAtme.setOnClickListener(relationClickListener);
    	
    	mTabActive = (Button)findViewById(R.id.user_center_btn_active);
    	mTabFavorite = (Button)findViewById(R.id.user_center_btn_blog);
    	
    	if( _uid == _hisuid ) {
    		mTabActive.setText("我的动态");
    		mTabFavorite.setText("我的收藏");
    	}
    	
    	mUserinfoDialog = new UserInfoDialog(UserCenter.this);
    	mUserface = (ImageView)mUserinfoDialog.findViewById(R.id.user_center_userface);
    	mUsername = (TextView)mUserinfoDialog.findViewById(R.id.user_center_username);
    	mFrom = (TextView)mUserinfoDialog.findViewById(R.id.user_center_from);
    	mSignature = (TextView)mUserinfoDialog.findViewById(R.id.user_center_signature);
    	mJointime = (TextView)mUserinfoDialog.findViewById(R.id.user_center_jointime);
    	
    	mUBL = (TextView)mUserinfoDialog.findViewById(R.id.user_center_booklist);
    	
    	if( _uid == _hisuid ) {
    		mUBL.setText("我的书单");
    	}
    	
    	mFBL = (TextView)mUserinfoDialog.findViewById(R.id.user_center_fbl);
    	mCBL = (TextView)mUserinfoDialog.findViewById(R.id.user_center_cbl);
    	mPBL = (TextView)mUserinfoDialog.findViewById(R.id.user_center_pbl);

    	mFavorites = (TextView)mUserinfoDialog.findViewById(R.id.user_center_favorites);
    	mFriends   = (TextView)mUserinfoDialog.findViewById(R.id.user_center_friends);
    	mFollowers = (TextView)mUserinfoDialog.findViewById(R.id.user_center_followers);
    	
    	mVoteCnt    = (TextView)mUserinfoDialog.findViewById(R.id.user_center_votecount); 
    	mBeVotedCnt = (TextView)mUserinfoDialog.findViewById(R.id.user_center_bevotedcount);
    	
    	mLatestonline = (TextView)mUserinfoDialog.findViewById(R.id.user_center_latestonline);
    	
    	mHeadTitle.setText(_username + " ▼");
    	

    	mTabActive.setEnabled(false);
    	mTabActive.setOnClickListener(tabBtnClick(mTabActive));
    	mTabFavorite.setOnClickListener(tabBtnClick(mTabFavorite));
    	
    	mBack.setOnClickListener(UIHelper.finish(this));
    	mRefresh.setOnClickListener(refreshClickListener);
    	mHeadTitle.setOnClickListener(headTitleClickListener);
    	mMessage.setOnClickListener(messageClickListener);
    	mAtme.setOnClickListener(atmeClickListener);
    	mUserinfoDialog.setOnCancelListener(dialogCancelListener);
    	
    	this.initLvActive();
    	this.initLvBookshelf();
    }    
    
    //初始化动态列表控件
    private void initLvActive() {
		
    	lvActive_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
    	lvActive_foot_more = (TextView)lvActive_footer.findViewById(R.id.listview_foot_more);
        lvActive_foot_progress = (ProgressBar)lvActive_footer.findViewById(R.id.listview_foot_progress);
        
    	lvActiveAdapter = new ListViewRecentTrendsAdapter(this, lvActiveData, R.layout.recent_trends_listitem, false); 
    	lvActive = (PullToRefreshListView)findViewById(R.id.user_center_activelist);
    	
    	lvActive.addFooterView(lvActive_footer);//添加底部视图  必须在setAdapter前
    	lvActive.setAdapter(lvActiveAdapter); 
    	
    	lvActive.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    			
				// 点击头部、底部栏无效
				if (position == 0 || view == lvActive_footer)
					return;

				Behavior behavior = null;
				// 判断是否是TextView
				if (view instanceof TextView) {
					behavior = (Behavior) view.getTag();
				} else {
					TextView tv = (TextView) view.findViewById(R.id.recent_trends_listitem_content);
					behavior = (Behavior) tv.getTag();
				}
				if (behavior == null)
					return;


				//UIHelper.showBooklistDetail(view.getContext(), booklist.getId());
        		
        	}
		});
    	
    	lvActive.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				lvActive.onScrollStateChanged(view, scrollState);
				
				//数据为空--不用继续下面代码了
				if(lvActiveData.size() == 0) return;
				
				//判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if(view.getPositionForView(lvActive_footer) == view.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}
				
				if(scrollEnd && curLvActiveDataState==UIHelper.LISTVIEW_DATA_MORE)
				{
					lvActive.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					lvActive_foot_more.setText(R.string.load_ing);
					lvActive_foot_progress.setVisibility(View.VISIBLE);
					
					//当前页数
					int pageIndex = lvActiveSumData/_pageSize;
					loadLvActiveData(_hisuid, mActiveHandler, pageIndex, UIHelper.LISTVIEW_ACTION_SCROLL);
				}
			}
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				lvActive.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
    	
    	lvActive.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
            public void onRefresh() {
				loadLvActiveData(_hisuid, mActiveHandler, 1, UIHelper.LISTVIEW_ACTION_REFRESH);
            }
        });
        
    }
    
    //初始化博客列表控件
    private void initLvBookshelf() {
    	
		lvBookshelfAdapter = new ListViewBookshelfAdapter(this, lvBookshelfData, R.layout.bookshelf_listitem);
		
		lvBookshelf_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
		lvBookshelf_foot_more = (TextView) lvBookshelf_footer.findViewById(R.id.listview_foot_more);
		lvBookshelf_foot_progress = (ProgressBar) lvBookshelf_footer.findViewById(R.id.listview_foot_progress);
		
		lvBookshelf = (PullToRefreshListView) findViewById(R.id.user_center_favoritelist);
		lvBookshelf.addFooterView(lvBookshelf_footer);// 添加底部视图 必须在setAdapter前
		lvBookshelf.setAdapter(lvBookshelfAdapter);
		
		lvBookshelf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					// 点击头部、底部栏无效
				if (position == 0 || view == lvBookshelf_footer)
					return;

				Bookshelf bookshelf = null;
				// 判断是否是TextView
				if (view instanceof TextView) {
					bookshelf = (Bookshelf) view.getTag();
				} else {
					TextView tv = (TextView) view.findViewById(R.id.bookshelf_listitem_title);
					bookshelf = (Bookshelf) tv.getTag();
				}
				if (bookshelf == null)
					return;


				//	UIHelper.showBooklistDetail(view.getContext(), bookshelf.getId() );
			}
		});
		
		lvBookshelf.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				lvBookshelf.onScrollStateChanged(view, scrollState);

				// 数据为空--不用继续下面代码了
				if (lvBookshelfData.isEmpty())
					return;

				// 判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(lvBookshelf_footer) == view.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}

				int lvDataState = StringUtils.toInt(lvBookshelf.getTag());
				if (scrollEnd && curLvBookshelfDataState == UIHelper.LISTVIEW_DATA_MORE) {
					lvBookshelf.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					lvBookshelf_foot_more.setText(R.string.load_ing);
					lvBookshelf_foot_progress.setVisibility(View.VISIBLE);
					// 当前pageIndex
					int pageIndex = lvBookshelfSumData / AppContext.PAGE_SIZE;
					loadLvBookshelfData( _hisuid, pageIndex, lvBookshelfHandler, UIHelper.LISTVIEW_ACTION_SCROLL );
							
				}
			}

			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {	
				lvBookshelf.onScroll(view, firstVisibleItem, visibleItemCount,totalItemCount);			
			}
		});
		
		lvBookshelf.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
			public void onRefresh() {
				loadLvBookshelfData( _hisuid, 1, lvBookshelfHandler, UIHelper.LISTVIEW_ACTION_REFRESH);
			}
		});

    }
    
    //初始化控件数据
	private void initData()
	{    	
		
		mUserHandler = new Handler(){
			public void handleMessage(Message msg) {
				
				headButtonSwitch(DATA_LOAD_COMPLETE);
				
				if(mUser != null){
					_username = mUser.getNickName();
					mHeadTitle.setText(_username + " ▼");
					mUsername.setText(mUser.getNickName());
					mFrom.setText(mUser.getLocation());
					mSignature.setText(mUser.getSummary());
					mJointime.setText(StringUtils.friendly_time(mUser.getJointime()));
					
					mFBL.setText( String.valueOf(mUser.getFBLCount()) );
					mCBL.setText( String.valueOf(mUser.getCBLCount()) );
					mPBL.setText( String.valueOf(mUser.getPBLCount()) );
					
					mFavorites.setText( String.valueOf(mUser.getFavoriteCount()) );
					mFriends.setText( String.valueOf(mUser.getFriendCount()) );
					mFollowers.setText( String.valueOf(mUser.getFollowerCount()) );
					
					mVoteCnt.setText( String.valueOf(mUser.getVoteUpCount()) );
					mBeVotedCnt.setText( String.valueOf(mUser.getBeVotedCount()) );
					
					//mLatestonline.setText(StringUtils.friendly_time(mUser.getLatestonline()));
					
					mLatestonline.setText(StringUtils.friendly_time(mUser.getLastLoginTime()));
					
					//初始化用户关系 & 点击事件
					if( mUser.getFollowStatus() == true )
						mUser.setRelation(User.RELATION_TYPE_FANS_HIM);
					else
						mUser.setRelation(User.RELATION_TYPE_NULL);
					
					loadUserRelation(mUser.getRelation());
				
					//加载用户头像
					UIHelper.showUserFace(mUserface, mUser.getUserAvatar());
				}
			}
		};
		
		this.loadLvUserData(_hisuid, mUserHandler, UIHelper.LISTVIEW_ACTION_INIT);
		
		//////////////////////////////////////////////////////////////////////////////////
    	mActiveHandler = new Handler() {
			public void handleMessage(Message msg) {
				headButtonSwitch(DATA_LOAD_COMPLETE);
				lvActiveHandleMessage(msg);
			}
		};
		
		this.loadLvActiveData(_hisuid, mActiveHandler, 1 ,UIHelper.LISTVIEW_ACTION_INIT);
		//////////////////////////////////////////////////////////////////////////////////
		lvBookshelfHandler = new Handler() {
			public void handleMessage(Message msg) {
				headButtonSwitch(DATA_LOAD_COMPLETE);
				lvBookshelfHandleMessage(msg);
			}
		};
	
		this.loadLvBookshelfData(_hisuid, 1, lvBookshelfHandler, UIHelper.LISTVIEW_ACTION_INIT);
	
	}
	
	//加载动态列表
	private void loadLvUserData(final int uid, final Handler handler, final int action){  
		headButtonSwitch(DATA_LOAD_ING);
		
		new Thread(){
			public void run() {
				Message msg = new Message();
				boolean isRefresh = true;
	
				if(action == UIHelper.LISTVIEW_ACTION_REFRESH || action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				
				try {
					mUser = appContext.getUserInfo(uid, isRefresh);					
					
					msg.what = 1;
					msg.obj = mUser;
	            } catch (AppException e) {
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
	            }
				msg.arg1 = action;//告知handler当前action
                handler.sendMessage(msg);
			}
		}.start();
		
	}

	//加载动态列表
	private void loadLvActiveData(final int catalog, final Handler handler, final int pageIndex, final int action){  
		headButtonSwitch(DATA_LOAD_ING);
		
		new Thread() {
			public void run() {
				Message msg = new Message();
				
				boolean isRefresh = false;
				if (action == UIHelper.LISTVIEW_ACTION_REFRESH || action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				
				try {
					BehaviorList list = appContext.getUserBehavior(catalog, pageIndex, isRefresh);
					msg.what = list.getPageSize();
					msg.obj = list;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				msg.arg1 = action;
				handler.sendMessage(msg);
			}
		}.start();			
		
	}
	
	
	private void loadLvBookshelfData(final int catalog, final int pageIndex, final Handler handler, final int action) {
		
		headButtonSwitch(DATA_LOAD_ING);
		
		new Thread() {
			public void run() {
				Message msg = new Message();
				boolean isRefresh = false;		
				if (action == UIHelper.LISTVIEW_ACTION_REFRESH || action == UIHelper.LISTVIEW_ACTION_SCROLL)
					isRefresh = true;
				
				try {
					BookshelfList list = appContext.getBookshelfList(catalog, pageIndex, isRefresh);
					msg.what = list.getPageSize();
					msg.obj = list;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				msg.arg1 = action;
				handler.sendMessage(msg);
			}
		}.start();	
	}

	private void loadUserRelation(int relation){
		switch (relation) {
			case User.RELATION_TYPE_BOTH:
				mRelation.setCompoundDrawablesWithIntrinsicBounds(R.drawable.widget_bar_relation_del, 0, 0, 0);
				mRelation.setText("取消互粉");
				break;
			case User.RELATION_TYPE_FANS_HIM:
				mRelation.setCompoundDrawablesWithIntrinsicBounds(R.drawable.widget_bar_relation_del, 0, 0, 0);
				mRelation.setText("已关注");
				break;
			case User.RELATION_TYPE_FANS_ME:
				mRelation.setCompoundDrawablesWithIntrinsicBounds(R.drawable.widget_bar_relation_add, 0, 0, 0);
				mRelation.setText("加关注");
				break;
			case User.RELATION_TYPE_NULL:
				mRelation.setCompoundDrawablesWithIntrinsicBounds(R.drawable.widget_bar_relation_add, 0, 0, 0);
				mRelation.setText("加关注");
				break;
		}
		if(relation > 0)
			mRelation.setOnClickListener(relationClickListener);
	}
	
	private void lvActiveHandleMessage(Message msg){
		
		if(msg.what >= 0){
			BehaviorList blist = (BehaviorList)msg.obj;
			Notice notice = blist.getNotice();	
		
			switch (msg.arg1) {
			case UIHelper.LISTVIEW_ACTION_INIT:
			case UIHelper.LISTVIEW_ACTION_REFRESH:
			case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
				lvActiveSumData = msg.what;
				lvActiveData.clear();//先清除原有数据
				lvActiveData.addAll(blist.getBehaviorList() );
				break;
			case UIHelper.LISTVIEW_ACTION_SCROLL:
				lvActiveSumData += msg.what;
				if(lvActiveData.size() > 0){
					for(Behavior behavior1 : blist.getBehaviorList()){
						boolean b = false;
						for(Behavior behavior2 : lvActiveData){
							if(behavior1.getId() == behavior2.getId()){
								b = true;
								break;
							}
						}
						if(!b) lvActiveData.add(behavior1);
					}
				}else{
					lvActiveData.addAll(blist.getBehaviorList());
				}
				break;
			}
			if(msg.what<_pageSize){
				curLvActiveDataState = UIHelper.LISTVIEW_DATA_FULL;
				lvActiveAdapter.notifyDataSetChanged();
				lvActive_foot_more.setText(R.string.load_full);
			}
			else if(msg.what == _pageSize){	
				curLvActiveDataState = UIHelper.LISTVIEW_DATA_MORE;
				lvActiveAdapter.notifyDataSetChanged();
				lvActive_foot_more.setText(R.string.load_more);
			}
			//发送通知广播
			if(msg.obj != null){
			//	UIHelper.sendBroadCast(UserCenter.this, notice);
			}
		}
		else if(msg.what == -1){
			//有异常--显示加载出错 & 弹出错误消息
			curLvActiveDataState = UIHelper.LISTVIEW_DATA_MORE;
			lvActive_foot_more.setText(R.string.load_error);
			((AppException)msg.obj).makeToast(UserCenter.this);
		}
		if(lvActiveData.size()==0){
			curLvActiveDataState = UIHelper.LISTVIEW_DATA_EMPTY;
			lvActive_foot_more.setText(R.string.load_empty);
		}
		lvActive_foot_progress.setVisibility(View.GONE);
		if(msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH){
			lvActive.onRefreshComplete(getString(R.string.pull_to_refresh_update) + new Date().toLocaleString());
			lvActive.setSelection(0);
		}else if(msg.arg1 == UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG){
			lvActive.setSelection(0);
		}
		
	}
	
	private void lvBookshelfHandleMessage(Message msg){
		
		if(msg.what >= 0){
			BookshelfList bsList = (BookshelfList)msg.obj;
			Notice notice = bsList.getNotice();
		
			switch (msg.arg1) {
			case UIHelper.LISTVIEW_ACTION_INIT:
			case UIHelper.LISTVIEW_ACTION_REFRESH:
			case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
				int newdata = 0;// 新加载数据-只有刷新动作才会使用到
				
				BookshelfList bslist = (BookshelfList) msg.obj;
				notice = bslist.getNotice();
				lvBookshelfSumData = msg.what;

				if (lvBookshelfData.size() > 0) {
					for (Bookshelf bookshelf1 : bslist.getBookshelfList()) {
						boolean b = false;
						for (Bookshelf bookshelf2 : lvBookshelfData) {
							if (bookshelf1.getId() == bookshelf2.getId()) {
								b = true;
								break;
							}
						}
						if (!b)
							newdata++;
					}
				} else {
					newdata = msg.what;
				}
				
				lvBookshelfData.clear();// 先清除原有数据
				lvBookshelfData.addAll(bslist.getBookshelfList());
				
				break;
			case UIHelper.LISTVIEW_ACTION_SCROLL:
				BookshelfList alist = (BookshelfList) msg.obj;
				notice = alist.getNotice();
				lvBookshelfSumData += msg.what;
				if (lvBookshelfData.size() > 0) {
					for (Bookshelf bookshelf1 : alist.getBookshelfList()) {
						boolean b = false;
						for (Bookshelf bookshelf2 : lvBookshelfData) {
							if (bookshelf1.getId() == bookshelf2.getId()) {
								b = true;
								break;
							}
						}
						if (!b)
							lvBookshelfData.add(bookshelf1);
					}
				} else {
					lvBookshelfData.addAll(alist.getBookshelfList());
				}
				
				break;
			}
			
			if(msg.what<_pageSize){
				curLvBookshelfDataState = UIHelper.LISTVIEW_DATA_FULL;
				lvBookshelfAdapter.notifyDataSetChanged();
				lvBookshelf_foot_more.setText(R.string.load_full);
			}
			else if(msg.what == _pageSize){	
				curLvBookshelfDataState = UIHelper.LISTVIEW_DATA_MORE;
				lvBookshelfAdapter.notifyDataSetChanged();
				lvBookshelf_foot_more.setText(R.string.load_more);
			}

		}
		else if(msg.what == -1){
			//有异常--显示加载出错 & 弹出错误消息
			curLvBookshelfDataState = UIHelper.LISTVIEW_DATA_MORE;
			lvBookshelf_foot_more.setText(R.string.load_error);
			((AppException)msg.obj).makeToast(UserCenter.this);
		}
		if(lvBookshelfData.size()==0){
			curLvBookshelfDataState = UIHelper.LISTVIEW_DATA_EMPTY;
			lvBookshelf_foot_more.setText(R.string.load_empty);
		}
		lvBookshelf_foot_progress.setVisibility(View.GONE);
		if(msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH){
			lvBookshelf.onRefreshComplete(getString(R.string.pull_to_refresh_update) + new Date().toLocaleString());
			lvBookshelf.setSelection(0);
		}else if(msg.arg1 == UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG){
			lvBookshelf.setSelection(0);
		}
		
	}
	
    /**
     * 头部按钮展示
     * @param type
     */
    private void headButtonSwitch(int type) {
    	switch (type) {
    	case DATA_LOAD_ING:
			mProgressbar.setVisibility(View.VISIBLE);
			mRefresh.setVisibility(View.GONE);
			break;
		case DATA_LOAD_COMPLETE:
			mProgressbar.setVisibility(View.GONE);
			mRefresh.setVisibility(View.VISIBLE);
			break;
		}
    }
	
	private View.OnClickListener tabBtnClick(final Button btn){
    	return new View.OnClickListener() {
			public void onClick(View v) {
		    	if(btn == mTabActive){
		    		mTabActive.setEnabled(false);
		    	}else{
		    		mTabActive.setEnabled(true);
		    	}
		    	if(btn == mTabFavorite){
		    		mTabFavorite.setEnabled(false);
		    	}else{
		    		mTabFavorite.setEnabled(true);
		    	}	    	
				
		    	
				if(btn == mTabActive){
					lvActive.setVisibility(View.VISIBLE);
					lvBookshelf.setVisibility(View.GONE);
					
					if(lvActiveData.size() == 0)
						loadLvActiveData(_hisuid, mActiveHandler, 1, UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG);
					
				}else{
					lvActive.setVisibility(View.GONE);
					lvBookshelf.setVisibility(View.VISIBLE);
					
					if(lvBookshelfData.size() == 0)
						loadLvBookshelfData(_hisuid, 1, lvBookshelfHandler, UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG);
				}
			}
		};
    }
	
	private View.OnClickListener refreshClickListener = new View.OnClickListener() {
		public void onClick(View v) {	
			loadLvUserData(_hisuid, mUserHandler, UIHelper.LISTVIEW_ACTION_INIT);
			loadLvActiveData(_hisuid, mActiveHandler, 1, UIHelper.LISTVIEW_ACTION_REFRESH);
			loadLvBookshelfData(_hisuid, 1, lvBookshelfHandler, UIHelper.LISTVIEW_ACTION_REFRESH);
		}
	};
	private View.OnClickListener headTitleClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			if(mUserinfoDialog != null && mUserinfoDialog.isShowing()){
				mHeadTitle.setText(_username + " ▼");
				mUserinfoDialog.hide();
			}else{
				mHeadTitle.setText(_username + " ▲");				
				mUserinfoDialog.show();
			}
		}
	};
	private DialogInterface.OnCancelListener dialogCancelListener = new DialogInterface.OnCancelListener(){
		public void onCancel(DialogInterface dialog) {
			mHeadTitle.setText(_username + " ▼");
		}		
	};	
	private View.OnClickListener messageClickListener = new View.OnClickListener() {
		public void onClick(View v) {	

			int followers = mUser != null ? mUser.getFollowerCount() : 0;
			int fans = mUser != null ? mUser.getFriendCount() : 0;
			
		   	if( _uid == _hisuid ) {
	    		UIHelper.showUserFriend(v.getContext(), _hisuid, FriendList.TYPE_FOLLOWER, fans, followers, "我的好友");
	    	}
		   	else {
		   		UIHelper.showUserFriend(v.getContext(), _hisuid, FriendList.TYPE_FOLLOWER, fans, followers, "TA的好友");
		   	}
		}
	};
	private View.OnClickListener atmeClickListener = new View.OnClickListener() {
		public void onClick(View v) {	
			if(mUser == null)	
				return;
			
		   	if( _uid == _hisuid ) {
		   		UIHelper.showUserBooklist(v.getContext(), _hisuid, 3, "我的书单");
	    	} else {
	    		UIHelper.showUserBooklist(v.getContext(), _hisuid, 3, "TA的书单");
	    	}
			
		}
	};

	private View.OnClickListener relationClickListener = new View.OnClickListener() {
		public void onClick(View v) {	

			if(mUser == null)	return;

			final AppContext ac = (AppContext)getApplication();
			
			/***
			if(!ac.isLogin()){
				UIHelper.showLoginDialog(UserCenter.this);
				return;
			}
			***/
			
			mMyProgress = ProgressDialog.show(v.getContext(), null, "加载中···",true,true);
			
			final Handler handler = new Handler(){
				public void handleMessage(Message msg) {
					
					if(mMyProgress!=null)
						mMyProgress.dismiss();
					
					if(msg.what == 1){
						MyResult res = (MyResult)msg.obj;
						if(res.OK()){
							
							if (mUser.getFollowStatus() == true) {
								mUser.setFollowStatus(false);
							} else {	
								mUser.setFollowStatus(true);
							}
							
							switch (mUser.getRelation()) {
								case User.RELATION_TYPE_BOTH:
									mRelation.setCompoundDrawablesWithIntrinsicBounds(R.drawable.widget_bar_relation_add, 0, 0, 0);
									mRelation.setText("加关注");
									mUser.setRelation(User.RELATION_TYPE_FANS_ME);
									break;
								case User.RELATION_TYPE_FANS_HIM:
									mRelation.setCompoundDrawablesWithIntrinsicBounds(R.drawable.widget_bar_relation_add, 0, 0, 0);
									mRelation.setText("加关注");
									mUser.setRelation(User.RELATION_TYPE_NULL);
									break;
								case User.RELATION_TYPE_FANS_ME:
									mRelation.setCompoundDrawablesWithIntrinsicBounds(R.drawable.widget_bar_relation_del, 0, 0, 0);
									mRelation.setText("取消互粉");
									mUser.setRelation(User.RELATION_TYPE_BOTH);
									break;
								case User.RELATION_TYPE_NULL:
									mRelation.setCompoundDrawablesWithIntrinsicBounds(R.drawable.widget_bar_relation_del, 0, 0, 0);
									mRelation.setText("已关注");
									mUser.setRelation(User.RELATION_TYPE_FANS_HIM);
									break;
							}
						}
						UIHelper.ToastMessage(UserCenter.this, res.getErrorMessage());
					}else{
						((AppException)msg.obj).makeToast(UserCenter.this);
					}
				}
			};
		
			new Thread(){
				public void run() {
					Message msg = new Message();
					MyResult res = null;
					try {
					
					//	Result res = ac.updateRelation(_uid, _hisuid, relationAction);
						
						if (mUser.getFollowStatus() == true) {
							res = ac.unfollowUser(_uid, _hisuid);
						} else {
							res = ac.followUser(_uid, _hisuid);
						}
						msg.what = 1;
						msg.obj = res;
		            } catch (AppException e) {
		            	e.printStackTrace();
		            	msg.what = -1;
		            	msg.obj = e;
		            }
	                handler.sendMessage(msg);
				}
			}.start();
			
			/***
			final Thread thread = new Thread(){
				public void run() {
					Message msg = new Message();
					try {
						Result res = ac.updateRelation(_uid, _hisuid, relationAction);
						msg.what = 1;
						msg.obj = res;
		            } catch (AppException e) {
		            	e.printStackTrace();
		            	msg.what = -1;
		            	msg.obj = e;
		            }
	                handler.sendMessage(msg);
				}
			};
			String dialogTitle = "";
			switch (mUser.getRelation()) {
				case User.RELATION_TYPE_BOTH:
					dialogTitle = "确定取消互粉吗？";
					relationAction = User.RELATION_ACTION_DELETE;
					break;
				case User.RELATION_TYPE_FANS_HIM:
					dialogTitle = "确定取消关注吗？";
					relationAction = User.RELATION_ACTION_DELETE;
					break;
				case User.RELATION_TYPE_FANS_ME:
					dialogTitle = "确定关注他吗？";
					relationAction = User.RELATION_ACTION_ADD;
					break;
				case User.RELATION_TYPE_NULL:
					dialogTitle = "确定关注他吗？";
					relationAction = User.RELATION_ACTION_ADD;
					break;
			}
			
			new AlertDialog.Builder(v.getContext())
			.setIcon(android.R.drawable.ic_dialog_info)
			.setTitle(dialogTitle)
			.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					thread.start();
					dialog.dismiss();
				}
			})
			.setNegativeButton(R.string.cancle, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			})
			.create().show();
			
			***/
		}
	};
}
